import { useMagicKeys } from "@vueuse/core";
import { watch, WatchStopHandle } from "vue";
import { Canvas } from "../canvas/Canvas";
import { useToolStore } from "../ToolBox/Tool";
import { Tools } from "../ToolBox/Tools";
import { UserHub, UserInput } from "./UserListener";
function binder<T>(
    oldBinder: WatchStopHandle[] | undefined,
    keyMaps: [T, string][],
    callback: (name: T, key: string) => void
) {
    oldBinder && oldBinder.forEach((i) => i());
    return keyMaps.map(([name, key]) => {
        return watch(keys[key], (v) => {
            if (v) callback.call(null, name, key);
        });
    });
}
type KeyArr<T> = [T, string][];
const keys = useMagicKeys();
const shotCuts = {
    HistoryMap: [
        ["cancel", "Ctrl+Z"],
        ["recover", "Ctrl+Y"],
        ["save", "Ctrl+S"],
    ] as KeyArr<keyof typeof UserInput>,

    ToolBoxMap: [
        [Tools.Paint, "G"],
        [Tools.Move, "V"],
        [Tools.Pen, "B"],
        [Tools.Eraser, "E"],
    ] as KeyArr<Tools>,
};

// 绑定键盘的操作
export class KeyBind {
    constructor() {
        this.rebuild();
    }
    rebuild() {
        this.ScaleStop && this.ScaleStop();
        this.bindHistoryRoller();
        this.bindToolBox();
        console.log("桌面端事件挂载完成");
    }

    private HistoryStops?: WatchStopHandle[];
    bindHistoryRoller() {
        const HistoryMap = shotCuts.HistoryMap;
        this.HistoryStops = binder(this.HistoryStops, HistoryMap, (name) =>
            UserInput[name]()
        );
    }

    private ToolBoxStops?: WatchStopHandle[];
    bindToolBox = () => {
        const ToolBoxMap = shotCuts.ToolBoxMap;
        this.ToolBoxStops = binder(this.ToolBoxStops, ToolBoxMap, (name) => {
            const store = useToolStore();
            store.changeTool(name);
        });
    };

    private ScaleStop?: Function;
    bindScale(canvas: Canvas) {
        const handle = (e: any) => {
            const step = e.wheelDelta > 0 ? 0.1 : -0.1;
            canvas.scale += step * canvas.scaleRate;
            UserHub.emit("scale", canvas.scale);
        };
        canvas.app.view.addEventListener("mousewheel", handle, {
            passive: true,
        });
        this.ScaleStop = () => {
            canvas.app.view.removeEventListener("mousewheel", handle);
        };
        return this.ScaleStop;
    }
}
